import store from "@/store";
const baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net"
let timeId
const request = {
  // 请求前
  invoke(args) {
    clearTimeout(timeId)
    timeId = setTimeout(() => {
      uni.showLoading({ title: '加载中' });
    }, 800)
    if (!args.url.startsWith("http")) {
      args.url = baseURL + args.url
    };
    args.header = {
      ...args.header, // 保留原本的 header
      "source-client": "miniapp", // 添加小程序端调用标识
    };
    //携带token
    if (store.state.user.profile) {
      args.header.Authorization = store.state.user.profile.token
    }
  },
  // 请求后
  complete(res) {
    // 关闭定时器
    clearTimeout(timeId)
    uni.hideLoading();
  },
}
uni.addInterceptor("request", request); //发送请求
uni.addInterceptor("uploadFile", request);//上传文件


export default (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          if (res.statusCode === 401) {
            // 跳转至登录页面
            uni.navigateTo({ url: "/pages/login/index" })
          }
          reject(res);
        }
      },
      fail(err) {
        reject(res);
      },
    });
  });
}
